<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>一键生成用户答题任务</span>
        </div>
      </template>
      <el-form :model="form" label-width="120px">
        <el-form-item label="Team ID">
          <el-input-number v-model="form.teamId" :min="1" placeholder="请输入Team ID" />
        </el-form-item>
        <el-form-item label="每日平均数量">
          <el-input-number v-model="form.averagePerDay" :min="1" placeholder="请输入每日平均数量" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" />
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="form.difficulties" multiple placeholder="请选择难度">
            <el-option v-for="item in 10" :key="item" :label="`难度 ${item}`" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreate" :loading="loading">创建任务</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>操作日志</span>
          <el-button @click="fetchLogs">刷新日志</el-button>
        </div>
      </template>
      <el-table :data="logs" style="width: 100%" border>
        <el-table-column prop="at" label="时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.at).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="动作" width="100">
          <template #default="{ row }">
            <el-tag>{{ row.action }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operator.name" label="操作人" width="120" />
        <el-table-column prop="detail" label="详情">
          <template #default="{ row }">
            <pre class="text-xs">{{ JSON.stringify(row.detail, null, 2) }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div v-if="row.action === 'create' && row.detail && row.detail.taskId">
              <el-button size="small" type="success" @click="handleStart(row.detail.taskId)">开始</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.detail.taskId)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  asynccreateuserquestioncreatetime,
  asynccreateuserquestionstart,
  asynccreateuserquestiondelete,
  asynccreateuserquestionlogs
} from '../../../api/index'

const loading = ref(false)
const logs = ref<any[]>([])

const form = reactive({
  teamId: undefined as number | undefined,
  averagePerDay: 10,
  startDate: '',
  endDate: '',
  difficulties: [] as number[]
})

const fetchLogs = async () => {
  try {
    const res = await asynccreateuserquestionlogs({ limit: 20 })
    if (res && Array.isArray(res)) {
      logs.value = res
    } else if (res && (res as any).data) {
       // Handle case where response might be wrapped
       logs.value = (res as any).data
    } else {
        // Fallback or check if the API returns a single object or array directly
        // Based on API definition: return fetchapi<LogEntry>(api.createuserquestionlogs, body)
        // It might return an array of LogEntry.
        logs.value = Array.isArray(res) ? res : []
    }
  } catch (error) {
    console.error('Failed to fetch logs', error)
  }
}

const handleCreate = async () => {
  if (!form.teamId || !form.startDate || !form.endDate || form.difficulties.length === 0) {
    ElMessage.warning('请填写完整信息')
    return
  }

  loading.value = true
  try {
    await asynccreateuserquestioncreatetime({
      teamId: form.teamId,
      averagePerDay: form.averagePerDay,
      startDate: new Date(form.startDate),
      endDate: new Date(form.endDate),
      difficulties: form.difficulties
    })
    ElMessage.success('创建成功')
    fetchLogs()
  } catch (error) {
    ElMessage.error('创建失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleStart = async (taskId: number) => {
  try {
    await ElMessageBox.confirm('确定要开始这个任务吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await asynccreateuserquestionstart({ teskId: taskId })
    ElMessage.success('任务已开始')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

const handleDelete = async (taskId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await asynccreateuserquestiondelete({ teskId: taskId })
    ElMessage.success('任务已删除')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 1rem;
}
</style>
